package ufabc.edu.helppo.gerador;

import java.util.List;

import org.hibernate.Session;

import ufabc.edu.helppo.persistencia.HibernateUtil;
import ufabc.edu.helppo.persistencia.entidades.Usuario;
import ufabc.edu.helppo.persistencia.entidades.InventoryFolders;
import ufabc.edu.helppo.persistencia.entidades.InventoryItems;
import com.eaio.uuid.*;
import org.hibernate.Session;
import org.hibernate.Transaction;
import ufabc.edu.helppo.persistencia.HibernateUtil;

public class Inventario {

	public static List<InventoryItems> listaItems(InventoryFolders folder) {
		Session session = HibernateUtil.getSessionFactory().openSession();
		List<InventoryItems> lista = (List<InventoryItems>) session
				.createQuery(
						"FROM InventoryItems WHERE parentFolderID = '"
								+ folder.getFolderID() + "'").list();
		session.close();
		return lista;
	}

	public static List<InventoryItems> listaItems(String folder) {
		Session session = HibernateUtil.getSessionFactory().openSession();
		List<InventoryItems> lista = (List<InventoryItems>) session
				.createQuery(
						"FROM InventoryItems WHERE parentFolderID = '" + folder
								+ "'").list();
		session.close();
		return lista;
	}

	public static InventoryFolders pegaFolder(String UUID) {
		Session session = HibernateUtil.getSessionFactory().openSession();
		List<InventoryFolders> folders = (List<InventoryFolders>) session.createQuery(
				"FROM InventoryFolders WHERE agentID = '" + UUID
						+ "' AND folderName='Helppo'").list();
		InventoryFolders folder;
		if (folders.size() == 0) {
			folder = criaPasta(UUID);
		} else {
			folder = folders.get(0);
		}
		session.close();
		return folder;
	}

	public static InventoryFolders pegaFolder(Usuario user) {
		return pegaFolder(user.getUUID());
	}

	public static InventoryFolders criaPasta(Usuario user) {
		return criaPasta(user.getUUID());
	}

	public static InventoryFolders criaPasta(String UUID) {
		Session session = HibernateUtil.getSessionFactory().openSession();
		Transaction tx = session.beginTransaction();

		// pasta raiz
		List<InventoryFolders> raiz = (List<InventoryFolders>) session
				.createQuery(
						"FROM InventoryFolders WHERE agentID = '"
								+ UUID
								+ "' AND parentFolderID='00000000-0000-0000-0000-000000000000'")
				.list();

		InventoryFolders folder = new InventoryFolders();
		folder.setFolderID((new UUID()).toString());
		folder.setAgentID(UUID);
		folder.setFolderName("Helppo");
		folder.setParentFolderID(raiz.get(0).getFolderID());
		folder.setType(10);
		folder.setVersion(1);
		session.persist(folder);
		tx.commit();

		return folder;
	}

}
